package com.zjzaki.thingsboard.activity.welcome;

import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import com.alibaba.fastjson.JSONObject;
import com.zjzaki.thingsboard.R;
import com.zjzaki.thingsboard.activity.login.LoginActivity;
import com.zjzaki.thingsboard.activity.main.MainActivity;
import com.zjzaki.thingsboard.dao.ThingsBoardDao;
import com.zjzaki.thingsboard.entity.LoginMsg;
import com.zjzaki.thingsboard.receiver.WifiReceiver;
import com.zjzaki.thingsboard.util.FileHelper;
import com.zjzaki.thingsboard.util.IPUtil;
import com.zjzaki.thingsboard.util.InternetUtil;
import com.zjzaki.thingsboard.util.Ping;

public class MyWelComeActivity extends AppCompatActivity {
    private Button btn_skip, btn_inter;
    private int totalNumber = 5;
    /**用于点击跳过或者进入应用按钮之后，界面发生跳转，但线程并未停止，时间到达，仍会重新渲染一次，
    使用此标志，用来控制不执行异步介绍的信息，从此达到中断的效果*/
    private boolean flag = true;
    boolean isPingOK = false;
    boolean isServerOK = false;
    private String ip = IPUtil.IP;

    Handler handler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if (msg.what == 0 && flag) {
                int count = countDown();
                btn_skip.setText("跳过 " + count);
                handler.sendEmptyMessageDelayed(0, 1000);
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (Build.VERSION.SDK_INT >= 21) {
            View decorView = getWindow().getDecorView();
            decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            getWindow().setStatusBarColor(Color.TRANSPARENT);
            //getSupportActionBar().hide();
        }
        setContentView(R.layout.activity_welcome);

        //注册WiFi监听
        IntentFilter filter = new IntentFilter();

        filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
        filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        registerReceiver(new WifiReceiver(), filter);

        //检查设备网络是否连接
        isServerOK = new InternetUtil(this).isInternetConnection();
        //检测能否与服务器通信
        // isPingOK = Ping.ping(ip, 3, 2);
        //判断设备是否联网和与服务器请求是否正确
        //isPingOK = isPingOK && internetConnection;
        //初始化界面
        initView();
    }

    /*5s之后自动跳转*/
    private void initView() {
        btn_skip = findViewById(R.id.btn_skip);
        btn_inter = findViewById(R.id.btn_inter);
        //按钮监听事件
        btn_skip.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                skip(v);
            }
        });
        btn_inter.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                intoApp(v);
            }
        });
        handler.sendEmptyMessageDelayed(0, 1000);
    }

    private int countDown() {
        if (totalNumber-- == 1) {
//            returnActivity(LoginActivity.class);
            intoActivity();
        }
        return totalNumber;
    }

    public void skip(View view) {
        flag = false;
//        returnActivity(LoginActivity.class);
        intoActivity();
    }

    public void intoApp(View view) {
        flag = false;
//        returnActivity(LoginActivity.class);
        intoActivity();
    }

    /**
     * 界面跳转
     *
     * @param activity 要跳转的界面
     */
    private void returnActivity(Class activity) {
        startActivity(new Intent(MyWelComeActivity.this, activity));
    }

    /**
     * 判断是否已登录，已登录直接进主界面
     */
    private void intoActivity() {
        //登录信息文件是否存在
        boolean fileFlag = false;

        //判断文件是否存在
        Context context = getApplicationContext();
        String[] strings = context.fileList();
        for (int i = 0; i < strings.length; i++) {
            if ("login.txt".equals(strings[i])) {
                fileFlag = true;
            }
        }

        //判断网络连接是否正常
        if (isServerOK){
            //判断是否有登录，true 主界面，false登录界面
            if (fileFlag) {
                /*
                 * 刷新token值
                 */
                FileHelper fileHelper = new FileHelper(this);
                LoginMsg loginMsg = fileHelper.getLoginMsg("login.txt");
                String s = ThingsBoardDao.refreshToken(loginMsg.getRefreshToken());
                JSONObject jsonObject = JSONObject.parseObject(s);
                //保存新的token值
                fileHelper.save("login.txt", jsonObject.getString("token") + " "
                        + jsonObject.getString("refreshToken") + " " + jsonObject.getString("scope"));
                returnActivity(MainActivity.class);
            } else {
                returnActivity(LoginActivity.class);
            }
        }else {
            Toast.makeText(this,"离线模式，请检查网络连接",Toast.LENGTH_LONG).show();
            returnActivity(MainActivity.class);
        }
    }

}
